package com.zjitc.serviceedu.utils;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component

public class VideoUtils implements InitializingBean {

    @Value("${aliyun.vod.file.keyid}")
    private String keyId;

    @Value("${aliyun.vod.file.keysecret}")
    private String keySecret;

    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;

    @Override
    public void afterPropertiesSet() throws Exception {

        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
    }
    // 初始化阿里云视频点播客户端
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) {
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai", // 点播服务的地区（请根据自己账户的地区选择）
                accessKeyId, accessKeySecret);
        return new DefaultAcsClient(profile);
    }

    // 获取视频时长
    public float getVideoDuration(String videoId) throws ClientException, com.aliyuncs.exceptions.ClientException {
        // 获取视频信息
        GetVideoInfoResponse response = getVideoInfo(videoId);
        if (response != null && response.getVideo() != null) {
            String status = response.getVideo().getStatus();
            if ("Normal".equals(status)) {
                // 视频状态为正常，获取时长
                return response.getVideo().getDuration();
            } else {
                System.out.println("视频正在处理，当前状态：" + status);
            }
        }
        return 0.0f; // 如果未能获取到时长，返回 0
    }

    // 获取视频信息，包括状态和时长
    private GetVideoInfoResponse getVideoInfo(String videoId) throws ClientException, com.aliyuncs.exceptions.ClientException {
        DefaultAcsClient client = initVodClient(VideoUtils.ACCESS_KEY_ID, VideoUtils.ACCESS_KEY_SECRET);
        GetVideoInfoRequest request = new GetVideoInfoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }
    // 获取视频文件大小
    public long getVideoSize(String videoId) throws ClientException, com.aliyuncs.exceptions.ClientException {
        // 使用阿里云的 API 来获取上传视频的元数据
        GetVideoInfoResponse response = getVideoInfo(videoId);
        if (response != null && response.getVideo() != null) {
            // 获取视频大小，返回值为字节（Byte）
            return response.getVideo().getSize();
        }
        return 0L; // 如果未能获取文件大小，返回0
    }

}
